<template>
  <div>
    <!-- <BreadCrumb></BreadCrumb>
    <x-card
      :message="message_card"
      :width="98"
      :height="height"
      style="margin: 20px 20px"
    > -->
    <!-- 搜索以及操作 -->
    <!-- 自定义组件 -->
    <x-search>
      <!-- 搜索的一系列东西 -->
      <template #search>
        <p>
          用户名
          <a-input
            v-model:value="name"
            placeholder="请输入用户名"
            style="width: 150px"
          />
        </p>
        <p style="margin-left: 20px">
          角色
          <a-select
            v-model:value="role"
            placeholder="请选择角色"
            style="width: 150px"
          >
            <a-select-option
              v-for="(value, index) in allrole_arr"
              :key="index"
              :value="value.id"
              >{{ value.name }}</a-select-option
            >
          </a-select>
        </p>
        <a-button type="primary" style="margin-left: 10px" @click="but_search"
          >搜索</a-button
        >
        <a-button style="margin-left: 10px" @click="reset_search"
          >重置</a-button
        >
      </template>
      <!-- 操作的一系列东西 -->
      <template #operate>
        <a-button
          type="primary"
          style="margin-left: 10px"
          @click="showModal"
          v-checkpermission:foo.bar="'system_user_add'"
          ><template #icon><plus-outlined style="margin-right: 0" /></template
          >新增用户</a-button
        >
        <!-- <a-button type="primary" style="margin-left: 10px" danger
          >批量删除</a-button
        > -->
      </template>
    </x-search>
    <!-- 谈话框--添加用户 -->
    <a-modal v-model:open="open" title="新增用户" @ok="handleOk">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="用户名" name="username">
          <a-input
            v-model:value="formState.username"
            placeholder="请输入用户名"
          />
        </a-form-item>
        <a-form-item label="真实姓名" name="truename">
          <a-input
            v-model:value="formState.truename"
            placeholder="请输入用户真实姓名"
          />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input
            v-model:value="formState.email"
            placeholder="请输入用户邮箱"
          />
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input
            v-model:value="formState.phone"
            placeholder="请输入用户手机号"
          />
        </a-form-item>
        <a-form-item label="角色" name="role">
          <a-select v-model:value="formState.role" placeholder="请选择角色">
            <a-select-option
              v-for="(value, index) in allrole_arr"
              :key="index"
              :value="value.id"
              >{{ value.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="初始密码" name="password" disabled>
          <a-input v-model:value="formState.password" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 搜索下面的表格 -->
    <a-table
      :dataSource="dataSource"
      :columns="columns"
      :loading="loading"
      :row-selection="{
        selectedRowKeys: state.selectedRowKeys,
        onChange: onSelectChange,
      }"
      :pagination="{
        pageSize: state.pageSize,
        total: state.total,
        current: state.current,
        showSizeChanger: true, // 显示每页条数选择器
        pageSizeOptions: ['10', '20', '50'], // 自定义每页条数选项
        showTotal: (total) => `共 ${total} 条`, // 显示总条数
      }"
      @change="
        (pagination) => {
          console.log(pagination);
          state.pageSize = pagination.pageSize;
          state.total = pagination.total;
          state.current = pagination.current;
          user_list();
        }
      "
      :scroll="{ y: 600 }"
      v-checkpermission:foo.bar="'system_user_list'"
    >
      <!-- :columns="columns" :data-source="data" @resizeColumn="handleResizeColumn" -->
      <!-- 头部表头默认显示，不需要操作 -->
      <!-- <template #headerCell="{ column }"></template> -->
      <!-- 身体-表格中的列表 -->
      <!-- <template #bodyCell="{ column, record }"> -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'role_name'">
          <!-- {{ record }} -->
          <span>
            <button
              :style="{
                border:
                  '1px solid ' + getRoleStyle(record.role_name).borderColor,
                backgroundColor: getRoleStyle(record.role_name).backgroundColor,
                borderRadius: '5px',
                color: getRoleStyle(record.role_name).color,
                padding: '0 8px',
                height: '24px',
                fontSize: '12px',
              }"
            >
              {{ record.role_name }}
            </button>
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <!-- 编辑按钮 -->
            <a-tooltip title="编辑" placement="top">
              <a-button
                type="text"
                size="small"
                @click="showModal_edit(record.id)"
                v-checkpermission:foo.bar="'system_user_edit'"
              >
                <template #icon>
                  <EditOutlined style="color: #1890ff; margin: 0" />
                </template>
                <span style="margin-left: 4px; color: #1890ff">编辑</span>
              </a-button>
            </a-tooltip>

            <!-- 重置密码按钮 -->
            <a-tooltip title="重置密码" placement="top">
              <a-button
                type="text"
                size="small"
                @click="reset_pwd(record.id)"
                v-checkpermission:foo.bar="'system_user_edit'"
              >
                <template #icon>
                  <KeyOutlined style="color: #52c41a; margin: 0" />
                </template>
                <span style="margin-left: 4px; color: #52c41a">重置密码</span>
              </a-button>
            </a-tooltip>

            <!-- 状态切换按钮 -->
            <a-tooltip
              :title="record.state === 0 ? '禁用' : '启用'"
              placement="top"
            >
              <a-button
                type="text"
                size="small"
                danger
                @click="
                  record.state === 0
                    ? del_user_f(record.id)
                    : start_user_f(record.id)
                "
                v-checkpermission:foo.bar="'system_user_delete'"
              >
                <template #icon>
                  <DeleteOutlined
                    style="margin: 0"
                    :style="{
                      color: record.state === 0 ? '#ff4d4f' : '#52c41a',
                    }"
                  />
                </template>
                <span
                  :style="{
                    color: record.state === 0 ? '#ff4d4f' : '#52c41a',
                  }"
                  >{{ record.state === 0 ? "禁用" : "启用" }}</span
                >
              </a-button>
            </a-tooltip>

            <!-- 真删除按钮（仅当状态为1时显示） -->
            <a-tooltip v-if="record.state === 1" title="删除" placement="top">
              <a-button
                type="text"
                size="small"
                danger
                @click="del_user_t(record.id)"
                v-checkpermission:foo.bar="'system_user_delete'"
              >
                <template #icon>
                  <DeleteOutlined style="color: #cf1322" />
                </template>
                <span style="margin-left: 4px; color: #cf1322">删除</span>
              </a-button>
            </a-tooltip>
          </a-space>
        </template>
      </template>
    </a-table>
    <!-- 谈话框--编辑用户 -->
    <a-modal v-model:open="open_edit" title="修改用户" @ok="handleOk_edit">
      <a-form
        ref="formRef_edit"
        :model="formState_edit"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState_edit.username" />
        </a-form-item>
        <a-form-item label="真实姓名" name="truename">
          <a-input v-model:value="formState_edit.truename" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState_edit.email" />
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="formState_edit.phone" />
        </a-form-item>
        <a-form-item label="角色" name="role">
          <a-select
            v-model:value="formState_edit.role"
            placeholder="请选择角色"
          >
            <a-select-option
              v-for="(value, index) in allrole_arr"
              :key="index"
              :value="value.id"
              >{{ value.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- </x-card> -->
  </div>
</template>

<script lang="ts" setup>
import XSearch from "./XSearch.vue";
import type { TableProps, TableColumnType } from "ant-design-vue";
import {
  ref,
  onMounted,
  reactive,
  computed,
  toRaw,
  createVNode,
  watch,
} from "vue";
import http from "../routerutils/http";
// 表单验证
import type { Rule } from "ant-design-vue/es/form";
import type { UnwrapRef } from "vue";
// 全局弹窗
import { message, Modal } from "ant-design-vue";
// 对话提示
import {
  EditOutlined,
  KeyOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";
import XSearchVue from "./XSearch.vue";
import { useStore } from "vuex";

// 角色样式渲染：
const roleStyles = {
  // 第一梯队：最高决策层（深色+金属质感）
  校长: {
    backgroundColor: "#e6f7ff", // 浅蓝背景
    borderColor: "#096dd9", // 深蓝边框（象征权威）
    color: "#003a8c", // 接近黑色的深蓝
    fontWeight: "bold",
    borderWidth: "2px",
    textShadow: "0 1px 1px rgba(0,0,0,0.1)", // 轻微文字阴影
    boxShadow: "0 2px 4px rgba(0,105,204,0.2)", // 投影效果
  },

  // 第二梯队：核心管理层（深色+警示色）
  管理员: {
    backgroundColor: "#fff2f0", // 浅红背景
    borderColor: "#a8071a", // 深红边框（象征权力）
    color: "#820014", // 深红文字
    fontWeight: "bold",
    borderWidth: "2px",
    letterSpacing: "0.5px", // 字间距加宽
  },

  // 第三梯队：部门负责人（深色专业色）
  教务主任: {
    backgroundColor: "#f0f5ff",
    borderColor: "#1d39c4", // 深蓝紫色
    color: "#10239e", // 深紫色
    fontWeight: "bold",
    borderWidth: "1.5px",
  },

  // 第四梯队：执行管理层（中等饱和度）
  班主任: {
    backgroundColor: "#fff7e6",
    borderColor: "#d46b08", // 标准橙色
    color: "#873800", // 深棕色
    borderWidth: "1.5px",
  },

  // 第五梯队：专业人员（专业色系）
  教师: {
    backgroundColor: "#fffbe6", // 更浅的米黄
    borderColor: "#d48806", // 金色
    color: "#876800", // 深金色
  },

  // 第六梯队：支持人员（浅专业色）
  教育: {
    backgroundColor: "#e6fffb", // 浅青
    borderColor: "#13c2c2", // 青色
    color: "#006d75", // 深青
  },

  宿管: {
    backgroundColor: "#f6ffed",
    borderColor: "#5b8c00", // 深绿
    color: "#3f6600", // 军绿
  },

  // 第七梯队：普通成员（低饱和度）
  学生: {
    backgroundColor: "#fafafa",
    borderColor: "#8c8c8c", // 中灰
    color: "#595959", // 深灰
    opacity: 0.9,
  },

  // 第八梯队：外部人员（最轻量级）
  访客: {
    backgroundColor: "#f5f5f5",
    borderColor: "#d9d9d9", // 浅灰
    color: "#bfbfbf", // 浅灰文字
    fontStyle: "italic",
    opacity: 0.7,
  },

  // 特殊角色示例（可根据需要扩展）
  系统: {
    backgroundColor: "#f9f0ff",
    borderColor: "#722ed1", // 紫色
    color: "#391085", // 深紫
    fontWeight: "bold",
    borderWidth: "1.5px",
  },
};
const getRoleStyle = (roleName: string) => {
  return (
    roleStyles[roleName] || {
      backgroundColor: "#f4f4f5",
      borderColor: "#d9d9d9",
      color: "#92969b",
    }
  );
};

const store = useStore();
const userPermiss_vuex = store.state.userPermiss;
// 创建一个自定义指令，来统一处理权限存在与否
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      // 移除元素
      el.parentNode?.removeChild(el);
    }
    console.log(el, binding);
    // el.classList.add("is-highlight");
  },
};

const message_card = ref<string>("");
const height = ref<string>("850px");
const name = ref<string>("");
const role = ref<number>();
// 1. 重置搜索的方法
const reset_search = () => {
  state.current = 1;
  name.value = "";
  role.value = null;
  user_list();
};
// 搜索按钮的方法-重新调用列表搜索的接口方法
const but_search = () => {
  user_list();
};
// 2. 搜索中角色
const allrole_arr = ref<string[]>([]);
// 所有角色的接口-方法
const role_all = async () => {
  try {
    const response = await http.get("/api/roles/allrole");
    console.log(response.data.results);
    allrole_arr.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};

// 3. 表格内容操作
type Key = string | number;
const loading = ref<boolean>(false);
// 表头
const columns = [
  {
    title: "用户名",
    dataIndex: "username",
    key: "username",
    width: 100,
  },
  {
    title: "真实姓名",
    dataIndex: "truename",
    key: "truename",
    width: 100,
  },
  {
    title: "邮箱",
    dataIndex: "email",
    key: "email",
    width: 180,
  },
  {
    title: "手机号",
    dataIndex: "phone",
    key: "phone",
    width: 160,
  },
  {
    title: "角色",
    dataIndex: "role_name",
    key: "role_name",
    width: 100,
  },
  {
    title: "操作",
    key: "action",
    width: 250,
  },
];
// 表中数据
const dataSource = ref<string[]>([]);
// 勾选框的一系列操作
const state = reactive<{
  selectedRowKeys: Key[];
  loading: boolean;
  pageSize: number;
  total: number;
  current: number;
}>({
  selectedRowKeys: [],
  loading: false,
  pageSize: 10,
  total: 100,
  current: 1,
});
const onSelectChange = (selectedRowKeys: Key[]) => {
  console.log("selectedRowKeys changed: ", selectedRowKeys);
  state.selectedRowKeys = selectedRowKeys;
};
// 表格中页码的设置
// 请求后端列表接口
const user_list = async () => {
  try {
    loading.value = true; // 开始加载
    const response = await http.get("/api/users/userlist", {
      params: {
        username: name.value.trim(),
        userrole: role.value,
        page_size: state.pageSize,
        page: state.current,
      },
    });
    const users = response.data.results.users;
    // 为每个用户对象添加一个唯一的 key 值，这里使用用户的 id 作为 key
    dataSource.value = users.map((user, index) => ({
      ...user,
      key: user.id, // 确保每个用户对象都有一个唯一的 key 值
    }));
    state.total = response.data.results.total[0].count;
  } catch (error) {
    console.log("请求失败：：", error);
  } finally {
    loading.value = false; // 开始加载
  }
};

// 4. 添加用户一系列操作
// 添加用户的接口方法
const add_user = async () => {
  try {
    // username, password, email, phone, role_id, truename
    const response = await http.post("/api/users/adduser", {
      username: formState.username,
      truename: formState.truename,
      email: formState.email,
      phone: formState.phone,
      role_id: formState.role,
      password: formState.password,
    });
    console.log(response.data.msg);
    message.info(response.data.msg);
    // 添加成功时候调用列表
    user_list();
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 弹窗的关闭与否
const open = ref<boolean>(false);
// 打开谈话窗的按钮方法
const showModal = () => {
  open.value = true;
};
// 谈话框中点击确定的时候方法
const handleOk = () => {
  formRef.value
    .validate()
    .then(() => {
      console.log("values", formState, toRaw(formState));
      open.value = false;
      // 添加用户的接口
      add_user();
    })
    .catch((error) => {
      console.log("error", error);
    });
};
// 接口--修改和添加用一样的接口
interface FormState {
  username: string;
  truename: string;
  email: string;
  phone: string;
  role: number;
  password: number;
}
const labelCol = { span: 5 };
const wrapperCol = { span: 13 };
const formRef = ref();
// 表单元素
const formState: UnwrapRef<FormState> = reactive({
  username: "",
  truename: "",
  email: "",
  phone: "",
  role: null,
  password: '123456',
});
// 规则--修改和添加用一样的接口
const rules: Record<string, Rule[]> = {
  username: [
    { required: true, message: "请输入用户名字", trigger: "change" },
    { min: 2, max: 10, message: "长度为2到10个字符串", trigger: "blur" },
  ],
  truename: [
    { required: true, message: "请输入用户真实名字", trigger: "change" },
    { min: 2, max: 10, message: "长度为2到10个字符串", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "change" },
    {
      type: "string",
      pattern:
        /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "change" },
    {
      type: "string",
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  role: [
    {
      required: true,
      message: "请选择角色名",
      trigger: "change",
    },
  ],
  password: [
    { required: true, message: "请输入用户密码", trigger: "change" },
    { min: 5, max: 25, message: "长度最少为5个字符串", trigger: "blur" },
  ],
};
// 5. 修改用户一系列操作
// 修改用户--保存数据
const edit_id = ref<number>(); // 修改的id
const edit_save = async () => {
  try {
    const response = await http.post("/api/users/edit_set", {
      id: edit_id.value,
      username: formState_edit.username,
      truename: formState_edit.truename,
      email: formState_edit.email,
      phone: formState_edit.phone,
      role_id: formState_edit.role,
    });
    if (response.data.code === 0) {
      message.success(response.data.msg);
      user_list();
    }
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 弹窗的关闭与否
const open_edit = ref<boolean>(false);
const formRef_edit = ref();
// 表单元素
const formState_edit: UnwrapRef<FormState> = reactive({
  username: "",
  truename: "",
  email: "",
  phone: "",
  role: null,
});
// 打开谈话窗的按钮方法
const showModal_edit = async (id: number) => {
  // console.log(id)
  open_edit.value = true;
  // 修改用户--获取数据
  try {
    const response = await http.get("/api/users/edit_get", {
      params: {
        id: id,
      },
    });
    formState_edit.username = response.data.results[0].username;
    formState_edit.truename = response.data.results[0].truename;
    formState_edit.email = response.data.results[0].email;
    formState_edit.phone = response.data.results[0].phone;
    formState_edit.role = response.data.results[0].role_id;
    edit_id.value = response.data.results[0].id;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 谈话框中点击确定的时候方法
const handleOk_edit = () => {
  formRef_edit.value
    .validate()
    .then(() => {
      console.log("values", formState_edit, toRaw(formState_edit));
      open_edit.value = false;
      // 修改用户--保存数据
      edit_save();
    })
    .catch((error) => {
      console.log("error", error);
    });
};
// 6. 删除用户-软删除
const del_user_f = (id: number) => {
  // 删除用户的对话框
  Modal.confirm({
    title: "禁用用户",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要禁用此用户吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      console.log("OK");
      // 删除的接口
      try {
        const response = await http.get("/api/users/delete_f", {
          params: {
            id: id,
          },
        });
        console.log(response);
        const msg = response.data.msg;
        message.success(msg);
        // 删除成功时候调用列表
        user_list();
      } catch (error) {
        console.log("请求失败：：", error);
      }
    },
    onCancel() {
      console.log("Cancel");
    },
  });
};
const start_user_f = async (id: number) => {
  try {
    const response = await http.get("/api/users/start", {
      params: {
        id: id,
      },
    });
    console.log(response);
    const msg = response.data.msg;
    message.success(msg);
    // 删除成功时候调用列表
    user_list();
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 7. 重置用户密码
const reset_pwd = async (id: number) => {
  // 重置密码的对话框
  Modal.confirm({
    title: "重置密码",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要重置此用户的密码吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      // console.log("OK");
      try {
        const response = await http.get("/api/users/resetpwd", {
          params: {
            id: id,
          },
        });
        console.log(response);
        const msg = response.data.msg;
        message.success(msg);
      } catch (error) {
        console.log("请求失败：：", error);
      }
    },
    onCancel() {
      console.log("Cancel");
    },
  });
};
// 8. 删除用户-真删除
const del_user_t = (id: number) => {
  // 删除用户的对话框
  Modal.confirm({
    title: "删除用户",
    icon: createVNode(ExclamationCircleOutlined),
    content: "慎重: 此操作不可退回。您确定要删除此用户吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      console.log("OK");
      // 删除的接口
      try {
        const response = await http.get("/api/users/delete_t", {
          params: {
            id: id,
          },
        });
        console.log(response);
        const msg = response.data.msg;
        message.success(msg);
        // 删除成功时候调用列表
        user_list();
      } catch (error) {
        console.log("请求失败：：", error);
      }
    },
    onCancel() {
      console.log("Cancel");
    },
  });
};
// last. 钩子函数
onMounted(() => {
  role_all();
  user_list();
});
</script>

<style scoped>
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > .anticon + span),
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}
</style>